package hit.example.home;

import hit.example.Menu.ViewMenu;
import hit.example.Object.ObjWord;
import hit.example.delegate.IOnMenuClosed;
import hit.example.detail.DetailFm;
import hit.example.task.TaskDinh;
import hit.example.task.TaskType;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.telpoo.frame.model.BaseModel;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class HomeActivity extends MyHomeActivity implements TaskType {
	BaseModel baseModel;
	public static HomeActivity me;
	IOnMenuClosed iOnMenuClosed;
	private ListWordFm listWordFm;
	DetailFm detailFm;
	MyFragment cruFragment;

	public static HomeActivity getInstance() {
		return me;
	}

	public void pushDetail(ObjWord ObjWord, int from) {
		cruFragment = detailFm;
		detailFm.setData(ObjWord, from);

		pushFragments(TabId.home, detailFm, true, null);

	}

	public void pusListWordFm() {
		cruFragment = listWordFm;
		pushFragments(TabId.home, listWordFm, true, null);

	}

	/*
	 * public void pusListWordFm(ArrayList<ObjWord> ojs) { cruFragment =
	 * listWordFm; pushFragments(TabId.home, listWordFm, true, null);
	 * 
	 * }
	 */
	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@Override
	public void onCreate(Bundle savedInstanceState) {

		viewMenu = new ViewMenu(HomeActivity.this, this);

		File direct = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/Hit_Dict/db/");

		if (!direct.exists()) {
			direct.mkdirs();
		}
		File exist = new File(pathStorageUnzip + "anh_viet.sqlite");
		/*
		 * if (!exist.isFile()) { TaskDownloadFile task = new TaskDownloadFile(
		 * getContext(), "Downloading Data", pathStorage,
		 * "http://app.vietbao.vn/service/apptudien/data/anh_viet.zip", new
		 * Idelegate() {
		 * 
		 * @Override public void callBack(Object value, int where) { boolean
		 * status = (Boolean) value; if (status) {
		 * FileSupport.unpackZip(pathStorageUnzip, "db.zip"); File del = new
		 * File(pathStorage); del.delete(); showToast("Download Thành Công !");
		 * } } }); task.startDownload(); }
		 */
		if (!exist.isFile()) {

			DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
			DownloadManager.Request request = new DownloadManager.Request(
					Uri.parse("http://app.vietbao.vn/service/apptudien/data/anh_viet.zip"));
			showToast("Cập nhật dữ liệu cho lần đầu tiên !");

			request.setDestinationInExternalPublicDir("/Hit_Dict/db",
					"anh_viet.zip");
			dm.enqueue(request);
			finish();
		}
		super.onCreate(savedInstanceState);
		me = HomeActivity.this;
		// khai báo 2 fragment
		listWordFm = new ListWordFm();
		detailFm = new DetailFm(); //
		pusListWordFm();

		edtSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				openSeach(s.toString());

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		getSlidingMenu().setOnClosedListener(new OnClosedListener() {

			@Override
			public void onClosed() {

				iOnMenuClosed.onMenuClosed();

			}
		});
		setupTask();
	}

	/**
	 * Class ViewMenu se set listener nay de lang nghe su kien khi menu da dong
	 * lai khi click vao 1 row trong ViewMenu
	 * 
	 * @author naq
	 * @param iOnMenuClosed
	 */
	public void setDelegateOnMenuClosed(IOnMenuClosed iOnMenuClosed) {
		this.iOnMenuClosed = iOnMenuClosed;

	}

	public void hiddenInput() {
		InputMethodManager input = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		input.hideSoftInputFromWindow(edtSearch.getWindowToken(), 0);
	}

	public void setUptitle(String title) {
		tvTitle.setText("" + title);

	}

	public void setHide() {
		edtSearch.setVisibility(View.GONE);
		btnChuyendoi.setVisibility(View.GONE);

	}

	public void setShow() {
		edtSearch.setVisibility(View.VISIBLE);
		btnChuyendoi.setVisibility(View.VISIBLE);

	}

	public void changeTitle(String title) {
		tvTitle.setText(title);
	}


	public void setFont(TextView txt, Context context) {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		String strDate = sdf.format(c.getTime());
		Typeface custom_font = Typeface.createFromAsset(context.getAssets(),
				"fonts/UVNBaLe.TTF");
		txt.setText("@" + strDate + " - Trương Văn Định - HTTT k6");
		txt.setTypeface(custom_font);
	}

	public void captureUsingDrawingCache() {

		targetView.buildDrawingCache();
		Bitmap b1 = targetView.getDrawingCache();
		// copy this bitmap otherwise distroying the cache will destroy
		// the bitmap for the referencing drawable and you'll not
		// get the captured view
		Bitmap b = b1.copy(Bitmap.Config.ARGB_8888, false);
		BitmapDrawable d = new BitmapDrawable(b);
		// canvasView.setBackgroundDrawable(d);
		targetView.destroyDrawingCache();
		String saved = Images.Media.insertImage(this.getContentResolver(), b,
				"share", "picture");
		Intent shareIntent = new Intent();
		shareIntent.setAction(Intent.ACTION_SEND);
		shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(saved));
		shareIntent.setType("image/png");
		startActivity(Intent.createChooser(shareIntent, "->"));
	}

	public void openSeach(String key) {

		ArrayList<Object> arrsend = new ArrayList<Object>();
		arrsend.add(key);
		arrsend.add(ngonngu);

		TaskDinh db = new TaskDinh(baseModel, TASK_SEARCH_DATA, arrsend,
				getContext());
		baseModel.exeTask(null, db);
	}

	public void setupTask() {
		baseModel = new BaseModel() {

			@Override
			public void onSuccess(int taskType, ArrayList<?> list, String msg) {
				super.onSuccess(taskType, list, msg);

				switch (taskType) {
				case TASK_SEARCH_DATA:
					cruFragment.updateNewData((ArrayList<ObjWord>) list, 1);
					break;

				default:
					break;
				}

			}

			@Override
			public void onFail(int taskType, String msg) {
				super.onFail(taskType, msg);
			}
		};

	}

}
